package com.sojson.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.sojson.util.ThreadLocalUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务装饰器
 *
 * @author liu
 * @date 2022-06-25
 */
@Order(Ordered.LOWEST_PRECEDENCE)
@Slf4j
@Aspect
@Component
public class ScheduledAspect implements PointcutsBase {

    // 配置织入点
    @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
    public void scheduledPointCut() {}

    /**
     * 基于注解切换数据源
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("scheduledPointCut()")
    public Object pointCutAnno(ProceedingJoinPoint point) throws Throwable {
        int size = ThreadLocalUtil.HANDLERS.size();
        try {
            for (int i = 0; i < size; i++) {
                ThreadLocalUtil.HANDLERS.get(i).runByTask();
            }

            return point.proceed();
        } finally {
            for (int i = size - 1; i > -1; i--) {
                try {
                    ThreadLocalUtil.HANDLERS.get(i).finallys();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

}